const path = require('path');
const express = require('express');
const cors = require('cors');
const morgan = require('morgan');
const { init: initDB } = require('./db');
const logger = morgan('tiny');
const app = express();
const { ygoController } = require('./controller/ygo');
const { userController } = require('./controller/user');
const { cardPicController } = require('./controller/cardPic');
const { securityController } = require('./controller/security');
const { commonController } = require('./controller/common');
const { adController } = require('./controller/ad');
const { aiController } = require('./controller/ai');

app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(cors());
app.use(logger);
// 首页
app.get('/', async (req, res) => {
  res.sendFile(path.join(__dirname, 'index.html'));
});
// 更新计数
// app.post('/api/count', async (req, res) => {
//   const { action } = req.body;
//   if (action === 'inc') {
//     await Counter.create();
//   } else if (action === 'clear') {
//     await Counter.destroy({
//       truncate: true,
//     });
//   }
//   res.send({
//     code: 0,
//     data: await Counter.count(),
//   });
// });
// 获取计数
// app.get('/api/count', async (req, res) => {
//   const result = await Counter.count();
//   res.send({
//     code: 0,
//     data: result,
//   });
// });
// 小程序调用，获取微信 Open ID
app.get('/api/wx_openid', async (req, res) => {
  if (req.headers['x-wx-source']) {
    res.send(req.headers['x-wx-openid']);
  }
});
// app.get('/api/ygo/getCardPic', async (id) => {
//   if (!id) {
//     res.send({
//       code: -1,
//       msg: 'id不能为空',
//     });
//   }
//   const r = request({
//     url: `https://images.ygoprodeck.com/images/cards_cropped/${ id }.jpg`,
//     method: 'GET',
//     headers: { 'Content-Type': 'text/json' },
//   }, (error, response, body) => {
//     if (!error && response.statusCode === 200) {
//       res.send(body);
//     }
//   });
// });
ygoController(app);
userController(app);
cardPicController(app);
securityController(app);
commonController(app);
adController(app);
aiController(app);
const port = process.env.PORT || 80;
async function bootstrap() {
  await initDB();
  app.listen(port, () => {
    console.log('启动成功', port);
  });
}
bootstrap();
